<script setup lang="ts">
import { reactive, toRefs } from 'vue';
import { Icon } from '@iconify/vue';
import { IObject, ItemType, resultOptions, useTable } from '@/components/core/dynamic-table/helper';
import DynamicTable, { TableColumn, TableController } from '@/components/core/dynamic-table';
import { Columns } from './table-data';
import { ElSwitch, ElSelect, ElPagination, ElOption, ElSpace, ElTag } from 'element-plus';
import { SchemaForm, MultiperOptionsResult, useOptions } from '@/components/core/schema-form';
import { ref } from 'vue';
import { ADialogInstance } from '@/components/basic/dialog';
import { formItems } from './table-data';
import { DefaultService as Api } from '@/servers';
import { message } from '@/components/basic/message';
import { clearFormValidation } from '@/utils/clear';

type ModelActionItem = { model_id: string | number; action_id: (string | number)[] };
const schema = reactive({
  url: ['getRoleModelList', 'getRoleActionList'],
  params: [],
  mapper: [
    ['data', 'model_name', 'id'],
    ['data', 'action_name', 'id']
  ],
  options: [],
  labelMapper: [],
  form: {
    model_id: '',
    action_id: []
  }
});
const optionsState = reactive({ ...useOptions(schema), ...toRefs(schema) }) as MultiperOptionsResult;
const addNewModel = () => {
  if (!optionsState.form.model_id) return message.warn('请选择模型');
  tableState.form.role_model_actions = tableState.form.role_model_actions.filter(
    (i: ModelActionItem) => i.model_id !== optionsState.form.model_id
  );
  tableState.form.role_model_actions.push({
    model_id: optionsState.form.model_id,
    action_id: [...optionsState.form.action_id]
  });
  optionsState.form.model_id = '';
  optionsState.form.action_id = [];
};
const deleteNewModel = (row: ModelActionItem) => {
  tableState.form.role_model_actions = tableState.form.role_model_actions.filter(
    (i: ModelActionItem) => i.model_id !== row.model_id
  );
};

const base = reactive({
  query: 'getRoleList',
  delete: 'postRoleDelete',
  data: [],
  Params: ['page', 'size', 'qForm.name'],
  listUrl: 'data.list',
  sort: (a: ItemType, b: ItemType): number => a.id - b.id,
  page: 1,
  size: 14,
  total: 0,
  qForm: {
    // queryForm
    name: ''
  },
  form: {
    id: '',
    name: '',
    ename: '',
    description: '',
    role_model_actions: []
  },
  openEdit: async (row: IObject = {}) => {
    if (row.id) {
      message.loading();
      const res = await Api.getRoleDetail(row.id);
      Object.assign(tableState.form, res.data);
      message.destroy();
    }

    editDialogRef.value?.openModel(row.id ? 'Edit' : 'Add');
  }
});

const tableState = reactive({ ...useTable(base), ...toRefs(base) }) as resultOptions;

const editDialogRef = ref<ADialogInstance>();
const handleClose = () => clearFormValidation(tableState.form);

const submit = async () => {
  const { created_at, role_model_actions, ...rest } = tableState.form;
  await Api.postRoleEdit({ 'role_model_actions[]': role_model_actions, ...rest });
  clearFormValidation(tableState.form);
  new String(created_at);
};
</script>
<template>
  <div class="wh-full flex flex-col box-border pb-2">
    <TableController>
      <template #right>
        <a-button type="primary" @click="tableState.editRowItem!()">Add</a-button>
      </template>
    </TableController>
    <div class="overflow-y-auto w-full p-1 box-border" style="background-color: var(--el-bg-color)">
      <DynamicTable
        height="100%"
        :columns="Columns as unknown as TableColumn<any>[]"
        :default-expand-all="false"
        row-key="id"
        :data="tableState.data"
        v-loading="tableState.loading"
        show-overflow-tooltip
        header-row-class-name="table-header"
      >
        <!-- <ElTableColumn type="selection" width="55" /> -->
        <template #brand="{ scope }">
          <span>{{ scope.row.dict_item?.name || '-' }}</span>
        </template>
        <template #status="container">
          <ElSwitch
            class="ml-2"
            :modelValue="Boolean(container.scope.row.status)"
            active-text="是"
            inactive-text="否"
            inline-prompt
            @change="val => ((container.scope.row.status = val ? 1 : 0) || true) && submit(container.scope.row)"
            style="--el-switch-on-color: #13ce66"
          />
        </template>
        <template #reced="container">
          <ElSwitch
            class="ml-2"
            :modelValue="Boolean(container.scope.row.reced)"
            active-text="推荐"
            inactive-text="不推荐"
            inline-prompt
            @change="val => ((container.scope.row.reced = val ? 1 : 0) || true) && submit(container.scope.row)"
            style="--el-switch-on-color: #9c27b0"
          />
        </template>
        <template #operate="container">
          <a-button type="info" size="small" @click="tableState.editRowItem!(container.scope.row)">
            <!-- 编辑 -->
            <Icon icon="ant-design:edit-outlined" />
          </a-button>
          <a-button type="danger" size="small" @click="tableState.deleteRowItem!(container.scope.row)">
            <!-- 删除 -->
            <Icon icon="ant-design:delete-outlined" />
          </a-button>
        </template>
      </DynamicTable>
    </div>
    <TableController>
      <template #right>
        <el-pagination
          background
          layout="prev, pager, next"
          :page-size="tableState.size"
          :total="tableState.total"
          v-model:current-page="tableState.page"
          @change="tableState.pageCurrentChangeHandle"
        />
      </template>
    </TableController>
    <a-dialog ref="editDialogRef" title="Edit" width="1000" @close="handleClose" @confirm="submit" draggable>
      <SchemaForm
        :formItems="formItems as any"
        :model="tableState.form"
        label-width="100px"
        label-position="left"
        clearFormItem
        @reload-table-data="tableState.fetchData"
      >
        <template #model>
          <div class="w-full flex flex-col">
            <ElSpace class="mb-1" v-for="(item, index) in tableState.form.role_model_actions" :key="index">
              <div
                class="font-size-14px py-4px px-12px line-height-24px h-32px box-border border-solid border border-gray-3 rounded-4px w-100px"
              >
                {{ optionsState.labelMapper[0][item.model_id] }}
              </div>
              <div
                class="flex flex-row items-center gap-1 px-4px line-height-24px h-32px box-border border-solid border border-gray-3 rounded-4px w-700px"
              >
                <ElTag
                  :type="['primary', 'success', 'warning', 'danger'][i % 4] as any"
                  v-for="(i, k) in item.action_id"
                  :key="k"
                >
                  {{ optionsState.labelMapper[1][i] }}
                </ElTag>
              </div>
              <a-button type="danger" @click="deleteNewModel(item)"><Icon icon="ep:close" /></a-button>
            </ElSpace>
            <ElSpace class="mb-1">
              <ElSelect placeholder="model" v-model="optionsState.form.model_id" class="w-100px"
                ><ElOption
                  v-for="(item, index) in optionsState.options[0]?.options || []"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
              /></ElSelect>
              <ElSelect placeholder="action" v-model="optionsState.form.action_id" class="w-700px" multiple
                ><ElOption
                  v-for="(item, index) in optionsState.options[1]?.options || []"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
              /></ElSelect>
              <a-button type="primary" @click="addNewModel"><Icon icon="ep:plus" /></a-button>
            </ElSpace>
          </div>
        </template>
      </SchemaForm>
    </a-dialog>
  </div>
</template>

<style lang="scss" scoped></style>
